package com.ssly.media.manage.api;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;
import com.ssly.media.manage.configuration.BaiduAIPProperties;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

@Component
public class BaiduAIP {
    @Autowired
    private BaiduAIPProperties baiduAIPProperties;


    public File toAudioFile(String content) {
        AipSpeech aipSpeech = new AipSpeech(baiduAIPProperties.getAppId(), baiduAIPProperties.getApiKey(), baiduAIPProperties.getSecretKey());
        TtsResponse res = aipSpeech.synthesis(content, "zh", 1, null);
        byte[] data = res.getData();
        JSONObject res1 = res.getResult();
        if (data != null) {
            try {
                Util.writeBytesToFileSystem(data, "output.mp3");
                return new File("output.mp3");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (res1 != null) {
            System.out.println(res1.toString(2));
            return null;
        }
        return null;
    }

}
